import COS from 'cos-js-sdk-v5';
import {
  getCos
} from './api';
const mixin = {
  data() {
    return {
      Bucket: "static-1305598391",
      Region: "ap-shanghai", /* 存储桶所在地域，必须字段 */
      CosAuth: null,
      staticImgHeader: 'http://static-1305598391.file.myqcloud.com/',
      jinshiImgHeader: 'http://jinshi-1305598391.file.myqcloud.com/',
      percent: 0,
      uploadState: 'default',
      isUpload: false
    }
  },
  created() {

  },
  mounted() {
  },
  methods: {
    /**上传图片到腾讯云**/
    uploadFileToTencentClound(file,size) {
      let that = this;
      this.isUpload = true;
      let promise = new Promise(resolve => {
        let getCosAuth2 = (options, callback) => {
          callback(this.CosAuth)
        }
        this.getCosAuth(() => {
          var cos = new COS({
            getAuthorization: getCosAuth2//重点调用函数
          })
          console.log(file)
          // 获取文件后缀
          var pathArr = file.name.split('.')
          //  随机生成文件名称
          var fileRandName = Date.now() + "" + parseInt(Math.random() * 1000)

          if (file.uid) {
            var fileName = file.uid + '.webp'
          } else {
            var fileName = fileRandName + '.webp'
          }

          let PicOperations = { "is_pic_info": 1, "rules": [{ "fileid": fileName, "rule": size ? `imageMogr2/thumbnail/${size}>/format/webp` : 'imageMogr2/thumbnail/1080x2200>/format/webp' }] }
          cos.uploadFile(
            {
              Bucket: this.Bucket /* 存储桶 */,
              Region: this.Region /* 存储桶所在地域，必须字段 */,
              Key: fileName /* 文件名 */,
              StorageClass: 'STANDARD', // 上传模式, 标准模式
              Body: file, // 上传文件对象
              SliceSize: 1024 * 1024 * 5,
              Headers: {
                // 'Pic-Operations':
                //   {"is_pic_info": 1, "rules": [{"fileid": file.name, "rule": "imageMogr2/format/webp"}]}
                'Pic-Operations': JSON.stringify(PicOperations)
              },
              onProgress: function (info) {
                console.log('[cos.postObject-seccess]', JSON.stringify(info));
                let completeVal =
                  (info.loaded / info.total) * 100 || 0;
                console.log('completeVal,completeVal', completeVal)
                that.percent = completeVal;

              }
            },
            function (err, data) {
              console.log('[cos.postObject-err]', err || data);
              if (that.percent == 100) {
                that.uploadState = 'success';
              } else {
                that.uploadState = 'default';
              }
              if (that.Bucket == 'static-1305598391') {
                resolve({ url_path: 'http://static-1305598391.file.myqcloud.com/' + data.UploadResult.OriginalInfo.Key, url: data.UploadResult.OriginalInfo.Key })
              } else {
                resolve({ url_path: 'http://jinshi-1305598391.file.myqcloud.com/' + data.UploadResult.OriginalInfo.Key, url: data.UploadResult.OriginalInfo.Key })
              }
            }
          );
        })
      });
      return promise
    },
    /**删除腾讯云图片**/
    delFileToTencentClound(file) {
      console.log(file, bucket)
      let that = this;
      let promise = new Promise((resolve, reject) => {
        let getCosAuth2 = (options, callback) => {
          callback(this.CosAuth)
        }
        this.getCosAuth(() => {
          var cos = new COS({
            getAuthorization: getCosAuth2//重点调用函数
          })
          cos.deleteObject(
            {
              Bucket: this.Bucket /* 存储桶 */,
              Region: this.Region /* 存储桶所在地域，必须字段 */,
              Key: file.url /* 文件名 */
            },
            function (err, data) {
              console.log('[cos.postObject-err]', err, data);
              if (err) {
                this.$message.error(err)
              } else {
                resolve(data)
              }
            }
          );
        }, bucket)
      });
      return promise
    },
    getCosAuth(callback) {
      getCos({}).then(res => {
        this.Bucket = res.data.bucket;
        this.Region = res.data.region;
        this.CosAuth = {
          TmpSecretId: res.data.credentials.tmpSecretId,
          TmpSecretKey: res.data.credentials.tmpSecretKey,
          SecurityToken: res.data.credentials.sessionToken,
          // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
          StartTime: res.data.startTime, // 时间戳，单位秒，如：1580000000
          ExpiredTime: res.data.expiredTime, // 时间戳，单位秒，如：1580000900
        };
        callback()
      })
    }
  }
}
export default mixin
